package com.zt.ztyh.controller;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zt.ztyh.dto.BankcardsDto;
import com.zt.ztyh.dto.ChangeDto;
import com.zt.ztyh.dto.CreditDto;
import com.zt.ztyh.entity.*;
import com.zt.ztyh.exception.ZhentaoException;
import com.zt.ztyh.service.*;
import com.zt.ztyh.utils.IdWorker;
import com.zt.ztyh.vo.common.Result;
import com.zt.ztyh.vo.common.ResultCodeEnum;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author 王利明
 */
@RestController
@RequestMapping("/credit")
public class CreditController {

          @Autowired
          private CreditService creditService;
          @Autowired
          private RedisTemplate<String,String> redisTemplate;
          IdWorker idWorker=new IdWorker();
          @Autowired
          private UsercreditService usercreditService;
          @Autowired
          private FeginLevelService levelService;
          @Autowired
          private FeginUserService feginUserService;
          @Autowired
          private FeginREcording feginREcording;


           /**
            *修改密码： 原密码  新密码  信用卡卡号
            */
         @PutMapping("/change")
          public Result change(@RequestBody BankcardsDto bankcardsDto){
             String phone = bankcardsDto.getPhone();
             String code = bankcardsDto.getCode();

             if (!redisTemplate.opsForValue().get(phone + "_" + code).equals(code)){
                 throw new ZhentaoException(ResultCodeEnum.CAPTCHA_ERROR);
             }
          QueryWrapper<Credit> queryWrapper = new QueryWrapper<>();
          queryWrapper.eq("payPassword", bankcardsDto.getPaypassword());
          queryWrapper.eq("cardNumber", bankcardsDto.getCardnumber());
          Credit one = creditService.getOne(queryWrapper);
          if (one != null) {
            one.setPaypassword(bankcardsDto.getNewPaypassword());
            creditService.saveOrUpdate(one);
            return Result.build(one, ResultCodeEnum.SUCCESS);
           }
           return Result.build(null, ResultCodeEnum.DATA_ERROR);
          }

          /**
     * 注销或挂失：卡号 密码  持卡人  手机号
     */
          @PutMapping("/cancel")
         public Result cancel(@RequestBody ChangeDto changeDto)
         {
             String phone = changeDto.getPhone();
             String code = changeDto.getCode();

             if (!redisTemplate.opsForValue().get(phone + "_" + code).equals(code)){
                 throw new ZhentaoException(ResultCodeEnum.CAPTCHA_ERROR);
             }
             QueryWrapper<Credit> queryWrapper = new QueryWrapper<>();
             queryWrapper.eq("cardNumber", changeDto.getCardnumber());
             if (creditService.getOne(queryWrapper)==null) {
                 return Result.build(changeDto, ResultCodeEnum.DATA_ERROR);
             }
             queryWrapper.eq("payPassword", changeDto.getPaypassword());
             Credit one = creditService.getOne(queryWrapper);
             if (one==null) {
                 return Result.build(changeDto, ResultCodeEnum.LOGIN_ERROR);
             }
             queryWrapper.eq("phone", changeDto.getPhone());
             if(creditService.getOne(queryWrapper)==null){
                 return Result.build(changeDto, ResultCodeEnum.phone);
             }
             one.setStatus(changeDto.getStatus());
             return  Result.build(creditService.saveOrUpdate(one), ResultCodeEnum.SUCCESS);
         }
         @GetMapping("/banlan")
         public Result banlan(@RequestParam("phone")String phone)
         {
             System.out.println(phone);
             BigDecimal balance = new BigDecimal(0.00);
             QueryWrapper<Credit> queryWrapper = new QueryWrapper<>();
             queryWrapper.eq("phone", phone);
             List<Credit> list = creditService.list(queryWrapper);
             list.forEach(System.out::println);
             if (list.size()==0) {
                 return Result.build(null, ResultCodeEnum.DATA_ERROR);
             }else {
                 for (Credit credit : list) {
                    balance=balance.add(credit.getBalance());
                 }
             }
             System.out.println(balance);
             return Result.build(balance,200,"成功");

         }

         /**
      * 开卡： 持卡人  手机号  身份证号  密码  性别
      */

         @PostMapping("/open")
         public Result open(@RequestBody Credit credit,
                            @RequestParam("uid")String uid)
         {
             System.out.println("111111"+credit);
             System.out.println("111111"+uid);
             String phone = credit.getPhone();
             String code = credit.getCode();

             if (!redisTemplate.opsForValue().get(phone + "_" + code).equals(code)){
                 throw new ZhentaoException(ResultCodeEnum.CAPTCHA_ERROR);
             }
              Random random = new Random();
             long randomNumber = (long) (random.nextDouble() * Math.pow(10, 15)) + (long) Math.pow(10, 14);
             String sixteenDigitNumber = String.format("%016d", randomNumber);
             credit.setId(idWorker.nextId());
             credit.setCardnumber(sixteenDigitNumber);
             credit.setPaypassword("000000");
             creditService.save(credit);
             Usercredit usercredit=new Usercredit();
             usercredit.setCid(credit.getId());
             usercredit.setUid(Long.valueOf(uid));
             usercreditService.save(usercredit);
             return Result.build(credit, ResultCodeEnum.SUCCESS);
         }

         /**
     * 消费  判断可用额度
     */
         @PutMapping("/consume")
         public Result consume(@RequestParam("cardnumber") String cardnumber,
                               @RequestParam("balance") Integer balance)
         {
              QueryWrapper<Credit> queryWrapper = new QueryWrapper<>();
              queryWrapper.eq("cardNumber", cardnumber);
              Credit one = creditService.getOne(queryWrapper);
              if (one == null) {
                  return Result.build(null, ResultCodeEnum.DATA_ERROR);
              }
              if (one.getBalance().compareTo(new BigDecimal(balance)) < 0) {
                  return Result.build(null, ResultCodeEnum.STOCK_LESS);
              }
              one.setBalance(one.getBalance().subtract(new BigDecimal(balance)));
             creditService.saveOrUpdate(one);
             return Result.build(null, ResultCodeEnum.SUCCESS);
         }


           /**
          * 修改密码
          */
           @GetMapping("/balance")
           public Result balance(@RequestBody BankcardsDto bankcardsDto) {
                String phone = bankcardsDto.getPhone();
                String code = bankcardsDto.getCode();

                if (!redisTemplate.opsForValue().get(phone + "_" + code).equals(code)){
                    throw new ZhentaoException(ResultCodeEnum.CAPTCHA_ERROR);
                }
            if(redisTemplate.opsForValue().get(bankcardsDto.getPhone()+"_"+bankcardsDto.getCode())!=bankcardsDto.getCode()){
                return Result.build(bankcardsDto.getCode(), ResultCodeEnum.CAPTCHA_ERROR);
            }
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("cardNumber", bankcardsDto.getCardnumber());
            queryWrapper.eq("payPassword", bankcardsDto.getPaypassword());

                Credit one = creditService.getOne(queryWrapper);
                if (one==null){
                return Result.build(bankcardsDto, ResultCodeEnum.DATA_ERROR);
            }
            if (!one.getRealname().equals(bankcardsDto.getRealname())){
                return Result.build(bankcardsDto, ResultCodeEnum.DATA_ERROR);
            }
            if (!one.getIdcard().equals(bankcardsDto.getIdcard())){
                return Result.build(bankcardsDto, ResultCodeEnum.DATA_ERROR);
            }
            if (!one.getPhone().equals(bankcardsDto.getPhone())){
                return Result.build(bankcardsDto, ResultCodeEnum.DATA_ERROR);
            }
            one.setPaypassword(bankcardsDto.getNewPaypassword());
            creditService.saveOrUpdate(one);
            return Result.build(null, ResultCodeEnum.SUCCESS);
            }

         /**
         * 信用卡还款
         *每日0.05%
         */
         @PutMapping("/overdraft")
         @Schema(description = "信用卡还款")
         public Result overdraft(@RequestBody CreditDto creditDto) {
             QueryWrapper<Credit> queryWrapper = new QueryWrapper<>();
             queryWrapper.eq("cardNumber", creditDto.getCardnumber());
             queryWrapper.eq("payPassword", creditDto.getPaypassword());
             Credit one = creditService.getOne(queryWrapper);
             if (one != null){
                 one.setBalance(one.getBalance().subtract(creditDto.getBalance()));
                 creditService.saveOrUpdate(one);
//                 流水记录
                 ZtyhRecording ztyhRecording = new ZtyhRecording();
                 ztyhRecording.setAmount(creditDto.getBalance());
                 ztyhRecording.setMoneyin(Long.valueOf(creditDto.getCardnumber()));
                 ztyhRecording.setMoneyout(creditDto.getId());
                 ztyhRecording.setState(3);

                 feginREcording.addRecording(ztyhRecording);
             }


               return Result.build(null, ResultCodeEnum.SUCCESS);
         }

         /**
          * 信用卡借款 当日借当日还 不记息    日利率万分之五
          */

         @PutMapping("/repayment")
//         @Scheduled(cron = "0 0 0 10 * ")
         @Schema(description = "信用卡消费")
         public Result repayment(@RequestBody CreditDto creditDto) {
             User user=feginUserService.userid(creditDto.getId());
             Integer level = user.getCredit()+user.getAsset();
             ZtyhLevel ztyhLevel=levelService.getLevel(level);
             BigDecimal lines = BigDecimal.valueOf(ztyhLevel.getLines());
             String nowStr = DateUtil.now();
//             当前月份
             java.time.LocalDateTime currentDateTime = DateUtil.parse(nowStr).toLocalDateTime();
             int dayOfMonth1 = currentDateTime.getDayOfMonth();
             ZtyhRecording ztyhRecording = new ZtyhRecording();
             if(dayOfMonth1>10){
                 java.time.LocalDateTime previousMonthDateTime = currentDateTime.plusMonths(1);
                 java.time.LocalDate previousMonthDate = previousMonthDateTime.toLocalDate();
                 int previousMonth = previousMonthDate.getMonthValue();
                 int year = previousMonthDate.getYear();
                 Date date = DateUtil.parse("" + year + "-" + previousMonth + "-10 00:00:00");
                 long between = DateUtil.between(new Date(), date, DateUnit.DAY);
                 System.out.println("距离下次还款日还多少天" + between);
                 QueryWrapper queryWrapper = new QueryWrapper();
                 queryWrapper.eq("payPassword", creditDto.getPaypassword());
                 queryWrapper.eq("cardNumber", creditDto.getCardnumber());
                 Credit one = creditService.getOne(queryWrapper);
                 if (one == null) {
                     return Result.build(null, ResultCodeEnum.LOGIN_ERROR);
                 }
                 BigDecimal balance = creditDto.getBalance();
                 BigDecimal add = balance.add(balance.multiply(BigDecimal.valueOf(0.00005 * between)));
                 one.setBalance(one.getBalance().add(add));
                 ztyhRecording.setAmount(creditDto.getBalance());
                 ztyhRecording.setMoneyin(Long.valueOf(creditDto.getCardnumber()));
                 ztyhRecording.setMoneyout(creditDto.getId());
                 ztyhRecording.setState(3);
                 feginREcording.addRecording(ztyhRecording);
                 creditService.save(one);
                 return Result.build(one, ResultCodeEnum.SUCCESS);
             }else{
                 int year = currentDateTime.getYear();
                 int previousMonth = currentDateTime.getMonthValue();
                 Date date = DateUtil.parse("" + year + "-" + previousMonth + "-10 00:00:00");
                 long between = DateUtil.between(new Date(), date, DateUnit.DAY);
                 System.out.println("距离下次还款日还多少天" + between);
                 QueryWrapper queryWrapper = new QueryWrapper();
                 queryWrapper.eq("payPassword", creditDto.getPaypassword());
                 queryWrapper.eq("cardNumber", creditDto.getCardnumber());
                 Credit one = creditService.getOne(queryWrapper);
                 if (one == null) {
                     return Result.build(null, ResultCodeEnum.LOGIN_ERROR);
                 }
                 BigDecimal balance = creditDto.getBalance();
                 BigDecimal add = balance.add(balance.multiply(BigDecimal.valueOf(0.00005 * between)));
                 one.setBalance(one.getBalance().add(add));
                 if(one.getBalance().compareTo(lines)<1){
                     one.setBalance(one.getBalance().multiply(BigDecimal.valueOf(0.00002)));
                 }
                 ztyhRecording.setAmount(creditDto.getBalance());
                 ztyhRecording.setMoneyin(Long.valueOf(creditDto.getCardnumber()));
                 ztyhRecording.setMoneyout(creditDto.getId());
                 feginREcording.addRecording(ztyhRecording);
                 ztyhRecording.setState(3);
                 creditService.save(one);
                 return Result.build(one, ResultCodeEnum.SUCCESS);
             }
         }


          /**
         * 登录成功 之后  进行一个 信用卡信息查询
        */
        @GetMapping("/cardsole")
        public Result cardsole(@RequestParam("phone")String phone){
            QueryWrapper<Credit> queryWrapper = new QueryWrapper();
            queryWrapper.eq("phone",phone);
            List<Credit> list = creditService.list(queryWrapper);
            return Result.build(list, ResultCodeEnum.SUCCESS);
        }

}
